package com.nf.health.app.mydoctor.adapter;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.SectionIndexer;
import android.widget.TextView;

import com.hyphenate.easeui.EaseConstant;
import com.nf.health.app.Constants;
import com.nf.health.app.R;
import com.nf.health.app.adapter.OnMyClickListener;
import com.nf.health.app.adapter.ViewHolder;
import com.nf.health.app.chatservice.activity.ChatActivity;
import com.nf.health.app.customview.HeadListView;
import com.nf.health.app.customview.SwipeView;
import com.nf.health.app.inquiry.docdetail.DocDetailActivity;
import com.nf.health.app.models.DoctorVo;
import com.nf.health.app.utils.ActivityUtils;
import com.nf.health.app.utils.ImageLoaderUtils;
import com.nf.health.app.utils.ViewUtil;

import java.util.ArrayList;
import java.util.List;

/*
*
* 我的医生适配器
*/

public class GzDoctorAdapter extends BaseAdapter implements SectionIndexer, HeadListView.HeaderAdapter, AbsListView.OnScrollListener {

    protected static final String TAG = GzDoctorAdapter.class.getSimpleName();
    private Activity context;
    private List<DoctorVo> doctors;
    public ArrayList<SwipeView> unClosedSwipeView = new ArrayList<SwipeView>();

    public GzDoctorAdapter(Activity context, List<DoctorVo> doctors) {
        this.context = context;
        this.doctors = doctors;
    }
	/**
	 * 刷新列表
	 * @param doctors
	 */
	public void setMyGzDoctorNotifyDataChanged( List<DoctorVo> doctors) {
		this.doctors = doctors;
		notifyDataSetChanged();
	}


	@Override
	public int getCount() {
		if (doctors != null) {
			return doctors.size();
		}
		return 0;
	}
    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        final DoctorVo bean = doctors.get(position);
        final ViewHolder holder = ViewHolder.get(parent, convertView, R.layout.item_my_doctor_gz, position);
        ImageView iv_user_head_icon = holder.getView(R.id.iv_user_head_icon);
        ImageLoaderUtils.getinstance(context).getImage(iv_user_head_icon, bean.getHimg(), R.drawable.moren_doctor_image);

        if (TextUtils.isEmpty(bean.getDoctorname()) || bean.getDoctorname() == null || bean.getDoctorname().equals("")) {
            holder.setText(R.id.doctor_name, doctors.get(position).getNick());
        } else {
            holder.setText(R.id.doctor_name, doctors.get(position).getDoctorname());
        }
        //根据服务类型判断医生类型 1家庭医生服务，2咨询服务，3健康管理，4责任医生 0    5家庭责任医生 （绿色）  -1 代表关注医生
        String serviceType = bean.getServicetype();
        TextView tv_doctor_type = holder.getView(R.id.tv_doctor_type);
        TextView service_end_time = holder.getView(R.id.service_end);
        switch (serviceType) {
            case "1":
                ViewUtil.setMyTextViewBgShade(tv_doctor_type,R.drawable.shade_enpety_oval_green3,bean.getServicename(), ContextCompat.getColor(context,R.color.green3));
              //  doctorType.setImageResource(R.drawable.doctor_family);
                break;
            case "2":
                ViewUtil.setMyTextViewBgShade(tv_doctor_type,R.drawable.shade_enpety_oval_blue3,bean.getServicename(), ContextCompat.getColor(context,R.color.blue3));
              //  doctorType.setImageResource(R.drawable.doctor_consult);
                break;
            case "3":
                ViewUtil.setMyTextViewBgShade(tv_doctor_type,R.drawable.shade_enpety_oval_red2,bean.getServicename(), ContextCompat.getColor(context,R.color.red2));
               // doctorType.setImageResource(R.drawable.doctor_health_manage);
                break;
            case "4":
                ViewUtil.setMyTextViewBgShade(tv_doctor_type,R.drawable.shade_enpety_oval_purple,bean.getServicename(), ContextCompat.getColor(context,R.color.purple2));
                //doctorType.setImageResource(R.drawable.doctor_respons);
                break;
            case "5":// 家庭责任医生
                ViewUtil.setMyTextViewBgShade(tv_doctor_type,R.drawable.shade_enpety_oval_green,bean.getServicename(), ContextCompat.getColor(context,R.color.green));
                //  doctorType.setImageResource(R.drawable.doctor_family);
                break;
            case "-1":// 关注的医生
                ViewUtil.setMyTextViewBgShade(tv_doctor_type,R.drawable.shade_enpety_oval_orange4,"关注医生", ContextCompat.getColor(context,R.color.color1));
                //  doctorType.setImageResource(R.drawable.doctor_family);
                break;
            default://默认是关注的医生
                service_end_time.setVisibility(View.GONE);
                ViewUtil.setMyTextViewBgShade(tv_doctor_type,R.drawable.shade_enpety_oval_orange4,"关注医生", ContextCompat.getColor(context,R.color.color1));
                //doctorType.setImageResource(R.drawable.doctor_attention);
                break;
        }
        String service_endResult = "";
        if(!TextUtils.isEmpty(bean.getStatus())){
            String  status = bean.getStatus();
            switch (status){//
                case "2"://已开启
                    long endTime = bean.getEndtime();//后台已经计算好的剩余时间
                    if(endTime == -1){
                        //单词咨询
                        service_endResult =  "单次咨询";
                        service_end_time.setVisibility(View.VISIBLE);
                        service_end_time.setText(service_endResult);
                    }else  if(endTime > 1){
                        if(endTime /24/60/60/1000 >0 ){
                            int days = Math.round(endTime / (24 * 60 * 60 * 1000));
                            service_end_time.setVisibility(View.VISIBLE);
                            service_endResult = days+"天到期" ;
                            service_end_time.setText(service_endResult);
                        }else{
                            int hours = Math.round(endTime / (1 *  60 * 60 * 1000));
                            service_end_time.setVisibility(View.VISIBLE);
                            service_endResult = hours+"小时到期";
                            service_end_time.setText(service_endResult);
                        }
                    }
                    break;
                case "1":
                    service_endResult = "未开启";
                    service_end_time.setVisibility(View.VISIBLE);
                    service_end_time.setText(service_endResult);
                    break;
                case "-1":
                    service_endResult = "";
                    service_end_time.setVisibility(View.GONE);
                    break;
                default:
                    break;
            }
        }

        holder.setText(R.id.doctor_type, bean.getDepartment() + " | " +bean.getProfessional()  );
        holder.setText(R.id.doctor_hospitalname, TextUtils.isEmpty(bean.getHname()) ? "未填写地址" : "" + bean.getHname());
        SwipeView swipeView = holder.getView(R.id.swipeView);
        View ll_content = holder.getView(R.id.ll_content);
        View delete = holder.getView(R.id.delete);
        delete.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (listener != null)
                    listener.onClick(position, doctors.get(position).getDoctorid());
                unClosedSwipeView.clear();
            }
        });


        ll_content.setTag(position);
        ll_content.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (unClosedSwipeView.size() > 0) {
                    closeAllOpenedSwipeView();
                } else {
                    //根据服务类型判断医生类型 1家庭服务，2咨询服务，3健康管理，4责任医生 0 -1 代表关注医生
                    String serviceType = bean.getServicetype();
                    Constants.DoctorType doctorType ;
                    switch (serviceType) {
                        case "1":
                            doctorType = Constants.DoctorType.EFDoctorTypeFamilyDoctor;//家庭医生
                            break;
                        case "2":
                            doctorType = Constants.DoctorType.EFDoctorTypeOnceConsultDoctor;//单次问诊医生
                            break;
                        case "3":
                            doctorType = Constants.DoctorType.EFDoctorTypeHealthManager;//健康管理
                            break;
                        case "4":
                            doctorType = Constants.DoctorType.EFDoctorTypeResponseDoctor;//责任医生
                            break;
                        case "-1":
                            doctorType = Constants.DoctorType.EFDoctorTypeFamilyDoctor;//关注医生
                            break;
                        default://默认
                            doctorType = Constants.DoctorType.EFDoctorTypeSystemMessage;//关注医生
                            break;
                    }
                    if ("-1".equals(serviceType) || "0".equals(serviceType)){
                        //没有服务,跳到医生详情
                        Bundle docDetailBundle = new Bundle();
                        docDetailBundle.putString(DocDetailActivity.DOCTORID, bean.getDoctorid());
                        ActivityUtils.showActivity(context, DocDetailActivity.class, docDetailBundle);
                    }else{
                        String typeResult =   doctorType.getType();
                        //有服务,跳到聊天
                        Bundle bundle = new Bundle();
                        bundle.putString(EaseConstant.EXTRA_USER_ID, bean.getDoctorid());
                        bundle.putInt(EaseConstant.EXTRA_CHAT_TYPE, EaseConstant.CHATTYPE_SINGLE);
                        bundle.putString(ChatActivity.EXTRA_DOCTOR_TYPE,typeResult);
                        ActivityUtils.showActivity(context, ChatActivity.class, bundle);
                    }

                }
            }
        });
        //屏蔽取消关注
        /*swipeView.setOnSwipeStatusChangeListener(new SwipeView.OnSwipeStatusChangeListener() {

            @Override
            public void onSwiping(SwipeView swipingSwipeView) {
                if (!unClosedSwipeView.contains(swipingSwipeView)) {
                    closeAllOpenedSwipeView();
                }

                if (!unClosedSwipeView.contains(swipingSwipeView)) {
                    unClosedSwipeView.add(swipingSwipeView);
                }

            }

            @Override
            public void onOpen(SwipeView openedSwipeView) {
                for (int i = 0; i < unClosedSwipeView.size(); i++) {
                    if (unClosedSwipeView.get(i) != openedSwipeView) {
                        unClosedSwipeView.get(i).close();
                    }
                }
                if (!unClosedSwipeView.contains(openedSwipeView)) {
                    unClosedSwipeView.add(openedSwipeView);
                }
            }

            @Override
            public void onClose(SwipeView closedSwipeView) {
                unClosedSwipeView.remove(closedSwipeView);
            }
        });*/


        return holder.getConvertView();
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {

    }

    //滑动监听
    @Override
    public void onScroll(AbsListView view, int firstVisibleItem,
                         int visibleItemCount, int totalItemCount) {
    }

    @Override
    public int getHeaderState(int position) {
        int realPosition = position;
        if (realPosition < 0 || position >= getCount()) {
            return HEADER_GONE;
        }
        int section = getSectionForPosition(realPosition);
        int nextSectionPosition = getPositionForSection(section + 1);
        if (nextSectionPosition != -1
                && realPosition == nextSectionPosition - 1) {
            return HEADER_PUSHED_UP;
        }
        return HEADER_VISIBLE;
    }

    @Override
    public void configureHeader(View header, int position, int alpha) {
        // TODO Auto-generated method stub

    }

    @Override
    public Object[] getSections() {
        return null;
    }

    @Override
    public int getPositionForSection(int section) {
        return 0;
    }

    @Override
    public int getSectionForPosition(int position) {
        return 0;
    }

    private OnMyClickListener listener;

    public void setOnMyClickListener(OnMyClickListener listener) {
        this.listener = listener;
    }

    private void closeAllOpenedSwipeView() {
        for (int i = 0; i < unClosedSwipeView.size(); i++) {
            if (unClosedSwipeView.get(i).getSwipeStatus() != SwipeView.SwipeStatus.Close) {
                unClosedSwipeView.get(i).close();
            }
        }
    }
}
